package com.foreveross.chameleon;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.cordova.CordovaWebViewClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
//import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
//import android.widget.TextView;

import com.foreveross.BroadcastConstant;
import com.foreveross.ChameleonConstant;
import com.foreveross.URL;
import com.foreveross.chameleon.base.BaseFragmentActivity;
import com.foreveross.chameleon.manager.ApplicationSyncListener;
import com.foreveross.chameleon.manager.AutoDownloadHelper;
import com.foreveross.chameleon.manager.CubeContentManager;
import com.foreveross.chameleon.manager.CubeContentStatus;
//import com.foreveross.chameleon.manager.R;
import com.foreveross.chameleon.update.AutoCheckUpdateListener;
import com.foreveross.chameleon.update.CheckUpdateTask;
import com.foreveross.chameleonsdk.ChameleonSDK;
import com.foreveross.data.table.MessageDataModel;
import com.foreveross.pojo.CubeContent;
import com.foreveross.pojo.CubeModule;
import com.foreveross.pojo.Privilege;
import com.foreveross.pojo.UserPrivilege;
import com.foreveross.push.url.MessageConstants;
import com.foreveross.util.CommonUtil;
import com.foreveross.util.Preferences;
import com.google.gson.Gson;

public class CManagerModuleActivity extends BaseFragmentActivity {
	String url = "";
	Boolean isLocalContent = true;
	IntentFilter intentFilter = new IntentFilter();
	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {

			if (BroadcastConstant.ReceiveMessage.equals(intent.getAction())) {
				new RefreshThread().start();

			} else if (BroadcastConstant.ReceiveMessages.equals(intent
					.getAction())) {
				if (CommonUtil.isPad(context)) {
					String json = intent.getExtras().getString("message");
					receiveMessage(json);
				}
			}

			else if (BroadcastConstant.RefreshMainPage.equals(intent
					.getAction())) {
				String identifier = intent.getStringExtra("identifier");
				String type = intent.getStringExtra("type");
				CubeContentStatus contentStatus = CubeContentManager
						.getInstance().getmCubeContentStatus();
				CubeModule module = contentStatus
						.getIdentifier_new_version_map().get(identifier);
				if (module == null) {
					module = contentStatus
							.getCubeModuleByIdentifier(identifier);
					if (module != null) {
						if (module.isAutoDownload()) {
							// endAnimAutoDownload();
						}
					}
				}
				refreshMainPage(identifier, type, module);
			} else if (BroadcastConstant.RefreshModule.equals(intent
					.getAction())) {

				String identifier = intent.getStringExtra("identifier");
				String type = intent.getStringExtra("type");
				CubeContentStatus contentStatus = CubeContentManager
						.getInstance().getmCubeContentStatus();
				CubeModule module = contentStatus
						.getIdentifier_new_version_map().get(identifier);
				if (module == null) {
					module = contentStatus
							.getCubeModuleByIdentifier(identifier);
				}
				refreshModule(identifier, type, module);

			} else if (BroadcastConstant.UpdateProgress.equals(intent
					.getAction())) {
				String identifier = intent.getStringExtra("identifier");
				int progress = intent.getIntExtra("progress", 0);
				updateProgress(identifier, progress);
			} else if (BroadcastConstant.MODULE_AUTODOWNLOAD_FINISH
					.equals(intent.getAction())) {
				// 显示自动下载
				autodownloadlayout.setVisibility(View.GONE);
				// AutoDownloadHelper.getInstance().setAutoDownloadCount(0);
				progress.setText("已下载：" + "0" + "，总计需下载：" + "0");
			} else if (BroadcastConstant.MODULE_AUTODOWNLOAD_START
					.equals(intent.getAction())) {
				// 关闭自动下载
				autodownloadlayout.setVisibility(View.VISIBLE);
			} else if (BroadcastConstant.MODULE_AUTODOWNLOAD_PROGERSS
					.equals(intent.getAction())) {
				// int count =
				// AutoDownloadHelper.getInstance().getAutoDownloadCount();
				int count = AutoDownloadHelper.getInstance().getTotalCount();
				int downLoadCount = AutoDownloadHelper.getInstance()
						.getProgressCount();
				int failCount = AutoDownloadHelper.getInstance().getFailCount();
				progress.setText("成功：" + (count - downLoadCount - failCount)
						+ ",失败：" + failCount + "，总计需下载：" + count);
			} else if (BroadcastConstant.SecurityChange.equals(intent
					.getAction())) {
				stopTimer(timer);
				// syncPrivilege();
				syscContent(true);
			} else if (BroadcastConstant.SecurityChangeForFile.equals(intent
					.getAction())) {
				// syncPrivilegeFile();
				syscContent(false);
			}

			else if (BroadcastConstant.SecurityRefreshMainPage.equals(intent
					.getAction())) {
				Log.i("", "SecurityRefreshMainPage ================== ");
				CubeContent cubeContent = CubeContentManager.getInstance()
						.getCubeContent();
				Set<CubeModule> modules = cubeContent.getModules();
				refreshManagerPage();
				for (CubeModule cubeModule : modules) {
					refreshMainPage(cubeModule.getIdentifier(), "main",
							cubeModule);
					break;
				}

				if (CommonUtil.isPad(context)) {
					refreshPrivileges();
					System.out.println("调用了 pad  SecurityRefreshModuelDetail");
				}
				// Intent intent2 = new Intent();
				// String title = Preferences.getToken(Application.sharePref);
				// Notifier.notifyInfo(context, R.drawable.about_logo, 123,
				// "权限发生改变", title, intent2);
				// Toast.makeText(application.getApplicationContext(), "权限改变",
				// Toast.LENGTH_SHORT).show();
			} else if (BroadcastConstant.SecurityRoleChange.equals(intent
					.getAction())) {
//				AppStatus.USERLOGIN = false;
				// 默认模块权限
				String privileges = Preferences.getPrivileges();
				saveGuestApp(privileges);
				Preferences.saveUser(ChameleonConstant.GUEST);
				// 重新签到
				CheckInUtil.pushSecurity(context, ChameleonConstant.GUEST);
				CManagerModuleActivity.this.sendBroadcast(new Intent(
						BroadcastConstant.SecurityRefreshModuelDetail));

				CubeContent cubeContent = CubeContentManager.getInstance()
						.getCubeContent();
				Set<CubeModule> modules = cubeContent.getModules();
				for (CubeModule cubeModule : modules) {
					refreshMainPage(cubeModule.getIdentifier(), "main",
							cubeModule);
					break;
				}
				if (CommonUtil.isPad(context)) {
					refreshPrivileges();
					System.out.println("调用了 pad  SecurityRefreshModuelDetail");
				}
				loginOrLogout(false);

				// 弹出提示框提示角色改变
				AlertDialog.Builder builder = new AlertDialog.Builder(context);
				builder.setTitle("提示");
				builder.setMessage("你的帐户角色被改变，请重新登录");
				builder.setPositiveButton("确定", null);
				Dialog dialog = builder.create();
				dialog.show();
			}
		}
	};

	Timer timer = new Timer();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// url = "file:///android_asset/www/phone/index.html";
		// url = URL.PHONE_MAIN_URL;
		if (isPad()) {
			url = URL.PAD_MAIN_URL;
		} else {
			url = URL.PHONE_MAIN_URL;
		}
		loadMainContent(url);
		intentFilter.addAction(BroadcastConstant.MODULE_AUTODOWNLOAD_FINISH);
		intentFilter.addAction(BroadcastConstant.MODULE_AUTODOWNLOAD_START);
		intentFilter.addAction(BroadcastConstant.MODULE_AUTODOWNLOAD_PROGERSS);
		intentFilter.addAction(BroadcastConstant.ReceiveMessage);
		intentFilter.addAction(BroadcastConstant.UpdateProgress);
		intentFilter.addAction(BroadcastConstant.RefreshModule);
		intentFilter.addAction(BroadcastConstant.RefreshMainPage);
		intentFilter.addAction(BroadcastConstant.SecurityChange);
		intentFilter.addAction(BroadcastConstant.ReceiveMessages);
		intentFilter.addAction(BroadcastConstant.SecurityRefreshMainPage);
		intentFilter.addAction(BroadcastConstant.SecurityRoleChange);
		intentFilter.addAction(BroadcastConstant.SecurityChangeForFile);
		registerReceiver(receiver, intentFilter);
		startTimer(timer);

		Intent i = getIntent();
		if (i != null) {
			showModule(i);
		}

		// 设置详情页面的WebViewClient
		setDetailWebViewClient(new CordovaWebViewClient(this) {
			@Override
			public boolean shouldOverrideUrlLoading(WebView webview, String url) {
				if (CommonUtil.isPad(getApplicationContext())) {
					if (url.contains("cube-action=push")) {
						url = subUrl(url);
						Intent intent = new Intent(CManagerModuleActivity.this,
								CManagerModuleActivity.class);
						intent.putExtra("from", "web");
						intent.putExtra("url", url);
						startActivity(intent);
						return true;
					} else if (url.contains("cube-action=pop")) {
						showDetailContent(false);
						return true;

					} else if (url.endsWith("cube://exit")) {
						showDetailContent(false);
						return true;
					}
				}
				return super.shouldOverrideUrlLoading(webview, url);
			}
		});
		Preferences.saveUser(ChameleonConstant.GUEST);
	}

	public String subUrl(String url) {
		int start = url.indexOf("cube-action=push");
		int end = start + 16;
		String newUrl = "";
		if (url.indexOf("&") == -1 && start != -1) {
			newUrl = url.substring(0, (url.indexOf("cube-action=push") - 1))
					+ url.subSequence(end, url.length());
		} else if (url.indexOf("&") > -1 && start < url.indexOf("&")) {
			newUrl = url.substring(0, (url.indexOf("cube-action=push")))
					+ url.subSequence(end + 1, url.length());
		} else if (url.indexOf("&") > -1 && start > url.indexOf("&")) {
			newUrl = url.substring(0, url.indexOf("&"))
					+ url.subSequence(end, url.length());
		}
		return newUrl;
	}

	public void showModule(Intent intent) {
		Intent i = intent;
		if (i != null) {
			String moduleIdentifier = i.getStringExtra("moduleIdentifier");
			String className = i.getStringExtra("className");
			// String params = i.getStringExtra("parameters");
			String params[] = i.getStringArrayExtra("parameters");
			CubeContentStatus contentStatus = CubeContentManager.getInstance()
					.getmCubeContentStatus();
			CubeModule module = contentStatus
					.getModuleByIdentify(moduleIdentifier);

			if (CommonUtil.isPad(this) && module != null) {
				final String moduleUrl = CubeContentManager.getInstance()
						.getModuleUrl(this, module);
				if (module.getLocal() == null) {
					isLocalContent = false;
				} else {
					isLocalContent = true;
				}

				// 不存在页面 NoticeFragment 即时通讯没有
				if (moduleUrl != null && !moduleUrl.equals("")) {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							loadDetailContent(moduleUrl, isLocalContent, null);
						}
					});
				}

			} else {
				if (module != null) {
					Intent moduleIntent = null;
					if (module.getModuleType() != CubeModule.INSTALLED) {
						String identifier = MessageConstants.MESSAGE_IDENTIFIER;
						module = contentStatus.getModuleByIdentify(identifier);
					}
					moduleIntent = CubeContentManager.getInstance().showModule(
							this, module);
					if (moduleIntent != null) {
						if (params != null && params.length != 0) {
							moduleIntent.putExtra("parameters", params);
						}
						if (className != null && !className.equals("")) {

							moduleIntent.setClassName(getApplicationContext(),
									className);
						}
						startActivity(moduleIntent);
					}
				}
			}
		}
		checkUpdate(url);

	}

	private AutoCheckUpdateListener acuListener;
	private CheckUpdateTask updateTask;

	public void checkUpdate(String url) {
		// System.out.println("checkUpdate");
		// && url.contains("login") 修改触发更新监听
		if (url != null) {
			// System.out.println("checkUpdate====!=null");
			acuListener = new AutoCheckUpdateListener(this);
			updateTask = new CheckUpdateTask(this, CubeContentManager
					.getInstance().getCubeContent(), acuListener);
			updateTask.execute();
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		showModule(intent);

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterReceiver(receiver);
		if (updateTask.getStatus() != AsyncTask.Status.FINISHED) {
			updateTask.cancel(true);
		}
		stopTimer(timer);
	}

	public void refreshMainPage(String identifier, String type,
			CubeModule module) {
		String moduleMessage = new Gson().toJson(module);
		setMainJavaScript("refreshMainPage('" + identifier + "','" + type
				+ "','" + moduleMessage + "')");
		// setMainJavaScript("refreshManagerPage()");
		// appView.sendJavascript("refreshMainPage('" + identifier + "','" +
		// type
		// + "','" + moduleMessage + "')");
	}

	public void refreshManagerPage() {
		setMainJavaScript("refreshManagerPage()");
		// appView.sendJavascript("refreshMainPage('" + identifier + "','" +
		// type
		// + "','" + moduleMessage + "')");
	}

	public void refreshModule(String identifier, String type, CubeModule module) {
		String moduleMessage = new Gson().toJson(module);
		setMainJavaScript("refreshModule('" + identifier + "','" + type + "','"
				+ moduleMessage + "')");
		// appView.sendJavascript("refreshModule('" + identifier + "','" + type
		// + "','" + moduleMessage + "')");
	}

	public void updateProgress(String identifier, int progress) {
		setMainJavaScript("updateProgress('" + identifier + "','" + progress
				+ "')");
		Log.i("updateProgress", "updateProgress+++++++++" + progress);
		// appView.sendJavascript("updateProgress('" + identifier + "','"
		// + progress + "')");
	}

	public void receiveMessage(final String identifier, final int count,
			boolean display) {
		setMainJavaScript("receiveMessage('" + identifier + "'," + count + ","
				+ display + ")");
		// appView.sendJavascript("receiveMessage('" + identifier + "'," + count
		// + "," + display + ")");
	}

	public void receiveMessage(String json) {
		setDetailJavaScript("receiveMessages('" + json + "')");
		setMainJavaScript("receiveMessages('" + json + "')");
		// appView.sendJavascript("receiveMessages('" + json + "')");
		// appView.sendJavascript("receiveMessage('" + identifier + "'," + count
		// + "," + display + ")");
	}

	public void refreshPrivileges() {
		setMainJavaScript("refreshPrivileges()");
	}

	public void loginOrLogout(boolean s) {
		setMainJavaScript("loginOrLogout(" + s + ")");
		// appView.sendJavascript("receiveMessage('" + identifier + "'," + count
		// + "," + display + ")");
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		Dialog dialog = new AlertDialog.Builder(this).setTitle("提示")
				.setMessage("确定退出 ？")
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				})
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
//						AppStatus.USERLOGIN = false;
						String privileges = Preferences.getPrivileges();
						saveGuestApp(privileges);
						Preferences.saveUser("");
						dialog.dismiss();
						finish();
						ChameleonSDK.getCApplication().onExit();
					}
				}).create();
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			if (event.getAction() == KeyEvent.ACTION_UP) {
				if (popFragment()) {
					return true;
				}
				if (dialog.isShowing()) {
					dialog.dismiss();
					return true;
				} else {
					dialog.show();
					return true;
				}
			}
		}
		return super.dispatchKeyEvent(event);
	}

	class RefreshThread extends Thread {
		@Override
		public void run() {
			try {
				CubeContentStatus contentStatus = CubeContentManager
						.getInstance().getmCubeContentStatus();
				MessageDataModel messageDataModel = new MessageDataModel(
						CManagerModuleActivity.this);
				for (String identifier : contentStatus.getIdentifier_map()
						.keySet()) {
					if (!identifier.equals(MessageConstants.MESSAGE_IDENTIFIER)) {
						int count = messageDataModel
								.getIdentifierUnReadCount(identifier);
						CubeModule module = contentStatus
								.getCubeModuleByIdentifier(identifier);
						module.setMsgCount(count);
						receiveMessage(identifier, count, true);
					}
				}
				int messageCount = messageDataModel.getUnReadCount();
				CubeModule messageModule = contentStatus
						.getCubeModuleByIdentifier(MessageConstants.MESSAGE_IDENTIFIER);
				messageModule.setMsgCount(messageCount);
				receiveMessage(MessageConstants.MESSAGE_IDENTIFIER,
						messageCount, true);
				CubeContent cubeContent = CubeContentManager.getInstance()
						.getCubeContent();
				CubeContentManager.getInstance().save(
						CManagerModuleActivity.this, cubeContent);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	@Override
	protected void onResume() {
		new RefreshThread().start();
		CubeContent cubeContent = CubeContentManager.getInstance()
				.getCubeContent();
		Set<CubeModule> modules = cubeContent.getModules();
		for (CubeModule cubeModule : modules) {
			refreshMainPage(cubeModule.getIdentifier(), "main", cubeModule);
			break;
		}

		super.onResume();

	}

	public void refreshMainPageEvent() {
		CubeContent cubeContent = CubeContentManager.getInstance()
				.getCubeContent();
		Set<CubeModule> modules = cubeContent.getModules();
		for (CubeModule cubeModule : modules) {
			refreshMainPage(cubeModule.getIdentifier(), "main", cubeModule);
			break;
		}
	}

	private void saveGuestApp(String result) {
		try {
			JSONObject jb = new JSONObject(result);
			JSONArray jay = jb.getJSONArray("priviliges");
			int len = jay.length();
			ArrayList<String> getList = CubeContentManager.getInstance()
					.getUserPrivilege().getGetList();
			ArrayList<String> deleteList = CubeContentManager.getInstance()
					.getUserPrivilege().getDeleteList();
			ArrayList<String> privilegeList = CubeContentManager.getInstance()
					.getUserPrivilege().getPrivilegeList();
			deleteList.clear();
			getList.clear();
			privilegeList.clear();
			for (int i = 0; i < len; i++) {
				JSONArray jay2 = jay.getJSONArray(i);
				if (!privilegeList.contains(jay2.getString(1))) {
					privilegeList.add(jay2.getString(1));
				}

				if (UserPrivilege.GET.equals(jay2.getString(0))) {
					getList.add(jay2.getString(1));
				}

				if (UserPrivilege.DELETE.equals(jay2.getString(0))) {
					deleteList.add(jay2.getString(1));
				}
			}
			CubeContent cubeContent = CubeContentManager.getInstance()
					.getCubeContent();
			Set<CubeModule> modules = cubeContent.getModules();
			for (CubeModule cubeModule : modules) {
				if (privilegeList.contains(cubeModule.getIdentifier())) {
					List<Privilege> prList = new ArrayList<Privilege>();
					cubeModule.setPrivileges(prList);
				} else {
					cubeModule.setPrivileges(null);
				}
			}
			CubeContentStatus contentStatus = CubeContentManager.getInstance()
					.getmCubeContentStatus();
			contentStatus.init(cubeContent);
			CubeContentManager.getInstance().save(CManagerModuleActivity.this,
					cubeContent);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void startTimer(Timer timer) {
		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				CManagerModuleActivity.this.sendBroadcast(new Intent(
						BroadcastConstant.SecurityChangeForFile));
			}
		}, 10 * 1000 * 60, 10 * 1000 * 60);
	}

	private void stopTimer(Timer timer) {
		System.out.println("stop timer !!");
		timer.cancel();
	}

	public Dialog dialog;


	private void syscContent(final boolean showDialog) {
		CubeContent cubeApp = CubeContentManager.getInstance().getCubeContent();
		ApplicationSyncListener callback1 = new ApplicationSyncListener() {

			@Override
			public void syncStart() {

			}

			@Override
			public void syncFail() {

			}

			@Override
			public void syncFinish(String result) {
				syscPrivilege(showDialog);
			}

		};
		CubeContentManager.getInstance().syncContent(callback1, cubeApp,
				CManagerModuleActivity.this, showDialog, "正在同步");
	}

	private void syscPrivilege(final boolean showDialog) {
		ApplicationSyncListener callback2 = new ApplicationSyncListener() {

			@Override
			public void syncStart() {
			}

			@Override
			public void syncFail() {
			}

			@Override
			public void syncFinish(String result) {
				refreshManagerPage();
				refreshMainPageEvent();
				if (showDialog) {
					CManagerModuleActivity.this.sendBroadcast(new Intent(
							BroadcastConstant.SecurityRefreshModuelDetail));
					timer = new Timer();
					startTimer(timer);
				}
			}

		};
		String username = Preferences.getUserName();
		if ("".equals(username)) {
			return;
		} else {
			if(!username.equals(ChameleonConstant.GUEST)){
				CubeContentManager.getInstance().syncContentPrivilege(true,
						CManagerModuleActivity.this, username, callback2,
						"正在获取账户权限");
			} else {
				CubeContentManager.getInstance().syncContentPrivilege(
						showDialog, CManagerModuleActivity.this,
						ChameleonConstant.GUEST, callback2, "正在获取账户权限");
			}
		}
	}

}
